<?php

namespace Home\Model;

class TeamModel extends CommonModel {

    public function findTeamByPlayerId($player_id){
        $sql = "select b.*, a.player_id, a.is_in_charge, a.is_in " .
               "from kick_team_player a, kick_team b " .
               "where 1 " .
               "and a.team_id=b.team_id " .
               "and a.player_id={$player_id} " .
               "" .
               "order by b.create_time desc " .
               "" .
               ";";
        $dt = $this->query($sql);
        return $dt;
    }

    public function findTeam($team_id=""){
        $flt = array(
            'is_del' => 0,
        );
        if (!empty($team_id)) {
            $flt['team_id'] = $team_id;
        }
        $dt = $this->where($flt)->select();
        return $dt;
    }

    public function findTeams($teamIds=array()){
        $ids = array();
        foreach ($teamIds as $k => $v) {
            $ids[] = $v['team_id'];
        }
        $flt = array(
            'team_id' => array('in', $ids),
            'is_del' => 0,
        );
        $dt = $this->where($flt)->select();
        return $dt;
    }

    public function createTeam(){
        // insert
        $this->_auto = array(
            array('create_time','time',1,'function'),
            array('update_time','time',3,'function'),
        );
        $dt = $this->create();
        if (empty($_POST['team_id'])) {
            $rs = $this->add($dt);
        } else {
            $rs = $this->save($dt);
        }

        $ret = array();
        if ($rs) {
            $ret['status'] = true;
            $ret['msg'] = '操作成功！';
            $ret['dt']['team_id'] = $rs;
        } else {
            $ret['status'] = false;
            $ret['msg'] = $this->getError();
        }
        return $ret;
    }

    public function findAwayTeams($home_team_id){
        $flt = array(
            'team_id' => array('not in', $home_team_id),
            'is_del' => 0,
        );
        $dt = $this->where($flt)->select();
        return $dt;
    }

    public function findMatchTeam($match){

        $dt = array();
        $flt = array(
            'team_id' => $match['home_team_id'],
            'is_del' => 0,
        );
        $dt['home_team'] = $this->where($flt)->find();
        $flt = array(
            'team_id' => $match['away_team_id'],
            'is_del' => 0,
        );

        $dt['away_team'] = $this->find($flt);
        return $dt;
    }

}
